﻿using HandyControl.Controls;
using HandyControl.Data;
using IoTClient.Enums;
using QServices.Services;
using QServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;

namespace QControlCenter
{
	public  static  class PlcManager
	{
		//private static Dictionary<string, QMitsubishiPlc> PLCDic = new Dictionary<string, QMitsubishiPlc>();
		private static Dictionary<string, ModbusRtuOverTcpPlc> PLCDic = new Dictionary<string, ModbusRtuOverTcpPlc>();

        private static void InitQMitsubishiPlc()
		{
			var equips = AppRuntime.GetService().GetService<DeviceManagerService>().GetDosingEquipmentList();
			if (equips == null || equips.Count <= 0) return;
			for (int i = 0; i < equips.Count; i++)
			{
				if (string.IsNullOrWhiteSpace(equips[i].Ip)) continue;
				if (equips[i].Port <= 0) continue;
				if (string.IsNullOrWhiteSpace(equips[i].Region)) continue;
				try
				{
					//var tt = new QMitsubishiPlc(equips[i].Ip, equips[i].Port, MitsubishiVersion.Qna_3E);
					var tt = new ModbusRtuOverTcpPlc(equips[i].Ip, equips[i].Port);
					PLCDic.Add(equips[i].Region, tt);
				}
				catch (Exception ex)
				{
					Growl.ErrorGlobal(new GrowlInfo
					{
						Message = ex.Message,
						WaitTime = 6,
						IsCustom = true,
					});
					AppRuntime.Logger_Error(ex);
				}

			}

		}

		public static ModbusRtuOverTcpPlc GetQMitsubishiPlc(string region)
		{
            if (PLCDic.Count <= 0) InitQMitsubishiPlc();
            if (string.IsNullOrWhiteSpace(region)) return PLCDic["A"];
            var plc = PLCDic[region];
            return plc;
        }

        public static QMitsubishiPlc GetQMitsubishiPlc__(string region)
		{
			return default;
			//if(PLCDic.Count<=0) InitQMitsubishiPlc();
			//if (string.IsNullOrWhiteSpace(region)) return PLCDic["A"];
			//var plc = PLCDic[region];
			//return plc;
		}


	}
	
}
